using System.Collections.Generic;

namespace pal.SvnConf.Core
{
    //Understands representation of a Group in SVN configuration file
    public class Group : ISecurityPrincipal
    {
        private const char GROUP_NAME_PREFIX = '@';
        private const char SPACE = ' ';

        private string _name;
        private List<ISecurityPrincipal> _members;

        public Group(string name, List<ISecurityPrincipal> members)
        {
            _name = name.Trim();
            _members = members;
        }

        public string Name
        {
            get { return _name; }
        }

        public string ConfigurationUsageName
        {
            get { return GROUP_NAME_PREFIX + _name; }
        }

        public List<ISecurityPrincipal> Members
        {
            get { return _members; }
        }

        public static Group Parse(string line, PasswdFile passwdFile, AuthzFile authzFile)
        {
            string[] principalNames = line.Split('=')[1].Split(',');
            List<ISecurityPrincipal> securityPrincipals = new List<ISecurityPrincipal>();
            foreach (string principalName in principalNames)
            {
                if (isGroupName(principalName))
                    securityPrincipals.Add(authzFile.FindGroupByName(groupName(principalName)));
                else
                    securityPrincipals.Add(passwdFile.FindUserByName(principalName));
            }
            return new Group(line.Split('=')[0], securityPrincipals);
        }

        private static string groupName(string name)
        {
            return name.Trim(GROUP_NAME_PREFIX, SPACE);
        }

        private static bool isGroupName(string name)
        {
            return name.Trim().StartsWith(GROUP_NAME_PREFIX.ToString());
        }


        public override string ToString()
        {
            return ConfigurationUsageName;
        }
    }
}